package cn.lil.servlet;

import cn.lil.dao.UserDao;
import cn.lil.model.User;
import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.SQLException;

@WebServlet(name = "UserUpdateServlet", value = "/UserUpdateServlet")
public class UserUpdateServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String idStr = request.getParameter("id");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String email = request.getParameter("email");

        if (idStr == null || idStr.isEmpty()) {
            // 如果 id 参数为空，可以返回一个错误响应或重定向到错误页面
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "ID 参数不能为空");
            return;
        }
        int id = Integer.parseInt(idStr);
        UserDao userDao = new UserDao();
        User user = new User(id, username, password, email,null,null);
        System.out.println("servlet" + user);
        try {
            userDao.updateUser(user);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        RequestDispatcher dispatcher = request.getRequestDispatcher("/UserListServlet");
        dispatcher.forward(request, response);
    }
}
